<?php

namespace app\web\mongo;

use app\common\component\Mongo;
use app\common\component\ErrorCode;

/**
 * 模拟id
 * Class FakeIdMongo
 * @package app\web\mongo
 */
class FakeIdMongo extends Mongo
{
    public $tableName = 'fake_id';

    /**
     * 创建新表，冗余自增id
     * @param $tableName
     * @return int
     * @throws \Exception
     */
    private function insertCollectionData($tableName)
    {
        $data = [
            'collection_name' => $tableName,
            'max_id' => 1
        ];

        if (!$this->add($data)) {
            throw new \Exception('创建自增数据失败,collection_name : ' . $tableName, ErrorCode::RESPONSE_FAIL);
        }

        return 1;
    }

    /**
     * 更新自增id
     * @param $tableName
     * @param $maxId
     * @return int
     * @throws \Exception
     */
    private function updateCollectionData($tableName, $maxId)
    {
        $data = [
            'max_id' => $maxId + 1
        ];

        $filter = [
            'collection_name' => $tableName,
            'max_id' => $maxId
        ];

        if (!$this->update($data, $filter)) {
            throw new \Exception('修改自增数据失败,collection_name : ' . $tableName, ErrorCode::RESPONSE_FAIL);
        }

        return $maxId + 1;
    }

    /**
     * 为mongodb表虚拟增加一个id字段
     * 第一版本，用顺序的形式，去表里面查。之后的用redis？
     * @param $tableName
     * @return int
     */
    public function getNextId($tableName)
    {
        $data = (array)$this->find(['collection_name' => $tableName]);
        if (empty($data)) {
            return $this->insertCollectionData($tableName);
        } else {
            return $this->updateCollectionData($tableName, $data['max_id']);
        }
    }
}